package com.dy.handler;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.dy.entity.User;
import com.dy.service.UserService;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * @Author: dy
 * @date: 2024/5/7 12:42
 * @ClassDescription: mp自动填充
 */
@Component
public class MybatisPlusHandler implements MetaObjectHandler {

    @Resource
    private UserService userService;

    @Override
    public void insertFill(MetaObject metaObject) {
        this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, "createBy", String.class, this.getUserName());
        this.strictInsertFill(metaObject, "updateBy", String.class, this.getUserName());
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, "updateBy", String.class, this.getUserName());
    }

    private String getUserName(){
        User user = null;
        Long id = null;
        try{
            id = StpUtil.getLoginIdAsLong();
        }catch (NotLoginException e){
            e.printStackTrace();
        }

        if (ObjectUtil.isNotNull(id)) {
            user = userService.getById(id);
        }
        return user == null ? null : user.getUserName();
    }
}
